package apollo.generator.common.utils;

import apollo.generator.common.exception.CustomException;
import apollo.generator.modules.entity.ColumnEntity;
import apollo.generator.modules.entity.PreferenceEntity;
import apollo.generator.modules.entity.TableEntity;
import com.google.common.collect.Maps;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.WordUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * <Description>
 * 代码生成工具类
 * @author Jun Lee
 * @version 1.0
 * @createDate 2020/07/04 17:28
 * @see apollo.generator.common.utils
 */
public class GenerateUtils {


    /**
     * 生成代码
     * @param table 表信息
     * @param columns 列集合
     * @param zip zip流
     * @param preference 偏好信息
     * @throws CustomException
     */
    public static void generatorCode(TableEntity table,
                                     List<ColumnEntity> columns, ZipOutputStream zip,
                                     PreferenceEntity preference) throws CustomException {
        //配置信息
        Configuration config = getConfig();
        boolean hasBigDecimal = false;
        boolean hasList = false;
        //表名转换成Java类名
        String className = tableToJava(table.getTableName(), preference.getTablePrefix().split(","));
        table.setClassName(className);
        table.setClassname(StringUtils.uncapitalize(className));
        //列信息
        for (ColumnEntity column : columns) {
            String attrName = columnToJava(column.getColumnName());
            column.setAttrName(attrName);
            column.setAttrname(StringUtils.uncapitalize(attrName));
            //列的数据类型，转换成Java类型
            String attrType = config.getString(column.getDataType(), columnToJava(column.getDataType()));
            column.setDataType(attrType);

            if (!hasBigDecimal && attrType.equals("BigDecimal")) {
                hasBigDecimal = true;
            }
            if (!hasList && "array".equals(column.getExtra())) {
                hasList = true;
            }
            //是否主键
            if (column.isColumnKey()) {
                table.setPk(column);
            }
        }

        table.setColumnEntities(columns);

        //没主键，则第一个字段为主键
        if (table.getPk() == null) {
            table.setPk(table.getColumnEntities().get(0));
        }

        //设置velocity资源加载器
        VelocityContext context = getVelocityContext(table, preference, hasBigDecimal, hasList);

        //获取模板列表
        List<String> templates = getTemplates();
        for (String template : templates) {
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(template, "UTF-8");
            tpl.merge(context, sw);

            try {
                //添加到zip
                zip.putNextEntry(new ZipEntry(getFileName(template, table.getClassName(), preference.getBasePackage(),preference)));
                IOUtils.write(sw.toString(), zip, "UTF-8");
                IOUtils.closeQuietly(sw);
                zip.closeEntry();
            } catch (IOException e) {
                throw new CustomException("渲染模板失败，表名：".concat(table.getTableName()).concat("\r\n").concat(e.getMessage()) );
            }
        }
    }

    private static VelocityContext getVelocityContext(TableEntity table, PreferenceEntity preference, boolean hasBigDecimal, boolean hasList) {
        Properties prop = new Properties();
        prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        Velocity.init(prop);
        String mainPath = preference.getBasePackage();
        //封装模板数据
        HashMap<Object, Object> map = Maps.newHashMap();
        map.put("tableName", table.getTableName());
        map.put("comments", table.getTableComment());
        map.put("pk", table.getPk());
        map.put("className", table.getClassName());
        map.put("classname", table.getClassname());
        map.put("pathName", table.getClassname().toLowerCase());
        map.put("columns", table.getColumnEntities());
        map.put("hasBigDecimal", hasBigDecimal);
        map.put("hasList", hasList);
        map.put("mainPath", mainPath);
        map.put("author", preference.getAuthor());
        map.put("email", preference.getEmail());
        map.put("daoSuffix", preference.getDaoSuffix());
        map.put("pojoSuffix", preference.getPojoSuffix());
        map.put("datetime", DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
        return new VelocityContext(map);
    }

    /**
     * 表名转换成Java类名
     */
    public static String tableToJava(String tableName, String[] tablePrefixArray) {
        if (null != tablePrefixArray && tablePrefixArray.length > 0) {
            for (String tablePrefix : tablePrefixArray) {
                String trim = tablePrefix.trim();
                tableName = tableName.replace(trim, "");
            }
        }
        return columnToJava(tableName);
    }

    /**
     * 列名转换成Java属性名
     */
    public static String columnToJava(String columnName) {
        return WordUtils.capitalizeFully(columnName, new char[]{'_'}).replace("_", "");
    }

    /**
     * 获取配置信息
     */
    public static Configuration getConfig() throws CustomException {
        try {
            return new PropertiesConfiguration("gen.properties");
        } catch (ConfigurationException e) {
            throw new CustomException("获取配置文件失败: ".concat(e.getMessage()));
        }
    }


    public static List<String> getTemplates() {
        List<String> templates = new ArrayList<String>();
        templates.add("template/Entity.java.vm");
        templates.add("template/Dao.xml.vm");
        templates.add("template/Service.java.vm");
        templates.add("template/ServiceImpl.java.vm");
        templates.add("template/Controller.java.vm");
        templates.add("template/Dao.java.vm");
        return templates;
    }

    /**
     * 获取文件名
     */
    public static String getFileName(String template, String className, String packageName,PreferenceEntity preference) {
        String packagePath = "main" + File.separator + "java" + File.separator;
        if (StringUtils.isNotBlank(packageName)) {
            packagePath += packageName.replace(".", File.separator) + File.separator;
        }
        if (template.contains("Entity.java.vm")) {
            return packagePath + "pojo" + File.separator + className + preference.getPojoSuffix()+".java";
        }

        if (template.contains("Dao.java.vm")) {
            return packagePath + "dao" + File.separator + className + preference.getDaoSuffix()+".java";
        }

        if (template.contains("Service.java.vm")) {
            return packagePath + "service" + File.separator + className + "Service.java";
        }

        if (template.contains("ServiceImpl.java.vm")) {
            return packagePath + "service" + File.separator + "impl" + File.separator + className + "ServiceImpl.java";
        }

        if (template.contains("Controller.java.vm")) {
            return packagePath + "controller" + File.separator + className + "Controller.java";
        }

        if (template.contains("Dao.xml.vm")) {
            return "main" + File.separator + "resources" + File.separator + "mapper" + File.separator + className + preference.getDaoSuffix()+".xml";
        }

        return null;
    }
}
